package com.itheima.stargraph.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.stargraph.dto.request.UserLoginReqDTO;
import com.itheima.stargraph.dto.respone.UserLoginResDTO;
import com.itheima.stargraph.mapper.UserMapper;
import com.itheima.stargraph.pojo.User;
import com.itheima.stargraph.service.UserService;
import com.itheima.stargraph.utils.JWTUtils;
import org.springframework.stereotype.Service;

/**
 * 用户业务层
 *
 * @Author mr.zhang
 * Date 2025/6/9 11:31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 用户登录
     *
     * @return
     */
    @Override
    public UserLoginResDTO login(UserLoginReqDTO dto) {
        //1.判断用户用户名或手机号是否正确
        User user = this.lambdaQuery().eq(User::getUsername, dto.getUsername())
                .or()
                .eq(User::getMobile, dto.getPhone())
                .one();
        if (user==null){
            throw new RuntimeException("用户名或密码错误");
        }
        //2.判断用户密码是否正确
        boolean checkpw = BCrypt.checkpw(dto.getPassword(), user.getPassword());
        if (!checkpw){
            throw new RuntimeException("用户名或密码错误");
        }
        //3.判断用户状态是否正确
        if (user.getStatus()!=0){
            throw new RuntimeException("用户非法");
        }
        //4.生成令牌
        String jwtToken = JWTUtils.createJWT(user.getId(), user.getUsername());
        //5.封装数据并返回
        UserLoginResDTO resDTO = UserLoginResDTO.builder()
                .id(user.getId())
                .avatar(user.getAvatar())
                .name(user.getUsername())
                .token(jwtToken).build();

        return resDTO;
    }
}
